
  import { Component, OnInit,Input } from '@angular/core';
  import {NgForm, FormsModule,FormBuilder,FormGroup,Validators ,FormControl,FormControlName} from '@angular/forms';
  import { ActivatedRoute, Router, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot } from '@angular/router';
  import {Observable} from 'rxjs/Observable';
  import {UserLoginService} from './loginservice/login.service';
  import {User} from './model/user';
  import { Subject } from 'rxjs/Subject';
  import 'rxjs/add/operator/map';

  @Component({
    selector: 'login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss']
  })
  export class LoginComponent implements OnInit {
    public validateForm:FormGroup;
    public user:User=new User();

  @Input() nzValidateStatus:FormControlName;

  /**
   * 错误提示对应的键值对
   */
  public formError:any={
    "userName":"",
    "password":""
  }
  /**
   * 错误提示中对应键的值
   */
  public errorMsg:any={
    "userName":{
      "required":"用户名必填",
      "minlength":"用户名至少4个字符",
      "maxlength":"用户名至多16个字符",
    },
    "password":{
      "required":"密码必填",
      "minlength":"密码至少6个字符",
      "maxlength":"密码至多10个字符",
      "pattern":"密码由字母或数字组成"
    }
  }


    constructor(
      private fb:FormBuilder,
      public loginservice:UserLoginService,
      public router: Router,
    ) { }

    ngOnInit() {
      this.buildForm();
    }

    /**
     * 验证表单
     * 
     * @memberof LoginComponent
     */
    buildForm(){
      this.validateForm=this.fb.group({
        userName:[
          this.user.userName,
          [
            Validators.required,
            Validators.maxLength(16),
            Validators.minLength(4),
          ]
        ],
        password:[
          null,
          [
            Validators.required,
            Validators.minLength(6),
            Validators.maxLength(10),
            Validators.pattern("[a-zA-Z0-9]{6,10}")
          ]
        ],
        remember:[true],
      });
      this.validateForm.valueChanges.subscribe(data=>this.onValueChanged(data));
    }


    _submitForm(){
      if(this.validateForm.valid){      
        this.user=this.validateForm.value;
        this.loginservice.login(this.user).subscribe(
          data=>{
            if(data.msg){
              console.log(data.msg+"系统提示");
            }else{
              this.loginservice.triggerNextValue(data);
              this.router.navigateByUrl("/home");
            };
          },
          error=>{
            //请求发生错误的回调
            console.log(error);
          },
        )
      }
    // for (var i in this.validateForm.controls) {
    //   console.log( this.validateForm.controls[i].value);
    //   this.validateForm.controls[i].markAsDirty();
    // }
    }

    /**
     * const声明的变量被赋值后不能再改变
     * control.patchValue({userName:"ceskk"})可以动态修改某些控件的值，
     * @param data 
     */
  public onValueChanged(data?:any){
    if(!this.validateForm){
      return;
      }
    const form=this.validateForm; //重要的变量声明用const防止被重新赋值
    for(var field in this.formError){
        this.formError[field]="";//初始化错误信息，防止被覆盖
        const control=form.get(field);

        //patchValue函数会触发onValueChanged()事件，导致无限循环报错,patchValue()函数后面的代码是不会被执行的
        //var json="{\""+field+"\":\""+control.value+"aaa\"}";
        //console.log(JSON.parse(json));
        //let test:any=JSON.parse(json);
        //这是修改form中控件名称的值
        //form.patchValue(test);  
        //control.patchValue("看结果");  这是修改当前控件的值

        // if(control&&control.dirty){
        //     console.log("控件修改了");
        // }
        // if(control&&control.valid){
        //   console.log("控件验证通过");
        // }
        //验证不通过时
        if(control&&control.dirty&&!control.valid){
          console.log("进来了");
          //获取对应控件名称下的错误提示值(object类型)
          const messages=this.errorMsg[field];
          //根据
          for(var key in control.errors){
             //messages中不存在的key过滤掉,目的是只显示对应错误的提示值
              if(!messages[key]){
                continue;
              }
              this.formError[field]=messages[key];
              console.log(this.formError[field]);
              break;
          }
        }

    }
    
  }

    /**
     * 登录
     * 
     * @memberof LoginComponent
     */
  public login(){
      //this.loginservice.login()
      if(this.validateForm.valid){
        this.user=this.validateForm.value;
        this.loginservice.login(this.user);
           
      }
  }
  }
